from cv2 import imread,transform
from skimage import transform
from numpy import *


def F(x, y, img):  # 灰度分布
    return 0.3*img[x, y, 0]+0.59*img[x, y, 1]+0.11*img[x, y, 2]


def GeneralMatrix(p, q, img):  # 笛卡尔系几何矩
    m = 0
    for x in range(img.shape[0]):
        for y in range(img.shape[1]):
            m += (x**p)*(y**q)*(F(x, y, img))
    return m


def I0(img):
    return GeneralMatrix(1, 0, img)/GeneralMatrix(0, 0, img)


def J0(img):
    return GeneralMatrix(0, 1, img)/GeneralMatrix(0, 0, img)


def CentralMatrix(m, n, img):  # 中心矩
    u = 0
    I_0 = I0(img)
    J_0 = J0(img)
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            u += F(i, j, img)*((i-I_0)**m)*((j-J_0)**n)
    return u


def StandardizedCentralMoment(m, n, img):
     return CentralMatrix(m, n, img)/((GeneralMatrix(0, 0, img))**((m+n+2)/2))


def getFeature(path):
    img = imread(path)
    img = transform.resize(img, (128, 128))
    I20 = StandardizedCentralMoment(2, 0, img)
    I02 = StandardizedCentralMoment(0, 2, img)
    I11 = StandardizedCentralMoment(1, 1, img)
    I30 = StandardizedCentralMoment(3, 0, img)
    I12 = StandardizedCentralMoment(1, 2, img)
    I21 = StandardizedCentralMoment(2, 1, img)
    I03 = StandardizedCentralMoment(0, 3, img)
    C1 = I20+I02
    C2 = (I20-I02)**2+4*I11**2
    C3 = (I30-3*I12)**2+(3*I21-I03)**2
    C4 = (I30+I12)**2+(I21+I03)**2
    C5 = (I30-3*I12)*(I30+I12)*((I30+I12)**2-3*(I21+I03**2)) + \
        (3*I21-I03)*(I21+I03)*(3*(I30+I12)**2-(I21+I03)**2)
    C6 = (I20-I02)*((I30+I12)**2-(I21+I03)**2)+4*I11*(I30+I12)*(I21+I03)
    C7 = (3*I21-I03)*(I30+I12)*((I30+I12)**2-3*(I21+I03)**2) - \
        (I30-3*I12)*(I21+I03)*(3*(I03+I12)**2-(I21+I03)**2)
    return [C1, C2, C3, C4, C5, C6, C7]
